<!DOCTYPE html>
<html>

<body>
  <h1>HTML DOM Events</h1>
  <h2>The oninput Event</h2>

  <p>How to dynamically update a slider value with oninput.</p>

  <input type="range" oninput="myFunction(this.value)">
  <p id="demo"></p>

  <button onclick="getDevicesList()">getDevicesList</button>
  <button onclick="connectBluetoothDevice()">connect bluetooth</button>

  <button onclick="onDisconnected()">disconnect bluetooth</button>

  <button onclick="turning()">right turning</button>

  <input type="file" id="fileInput">



  <p>...</p>

  <button onclick="uvctest()">uvc test</button>

  <p>...</p>

  <button onclick="exposureTest()">exposureTest</button>



  <script>

    document.getElementById('fileInput').addEventListener('change', function selectedFileChanged() {
      console.log(this.files); // will contain information about the file that was selected.
    });


    function exposureTest() {
      navigator.mediaDevices.getUserMedia({ video: true })
        .then(mediaStream => {
          const track = mediaStream.getVideoTracks()[0];
          const imageCapture = new ImageCapture(track);
          console.log(imageCapture);

          imageCapture.getPhotoCapabilities()
            .then(photoCapabilities => {
              const settings = track.getSettings();
              console.log(settings);
              console.log(photoCapabilities);

              // Check if exposure compensation is supported or not
              if (photoCapabilities.exposureCompensation) {
                settings.exposureCompensation = photoCapabilities.exposureCompensation.max; // Or any value.
              }

              track.applyConstraints(settings)
                .catch(error => console.error('applyConstraints() error:', error));
            });
        });
    }

    function uvctest() {
      console.log("Hello World");

      var http = require("http");
      console.log(http)

      // const filters = [
      //   { vendorId: 7119 }
      // ];
      // // 获取已链接的设备
      // navigator.usb.getDevices().then(devices => {
      //   console.log(devices)
      // });

      // // 请求连接设备
      // navigator.usb.requestDevice({ filters })
      //   .then((usbDevice) => {
      //     console.log(usbDevice);
      //     console.log(`Product name: ${usbDevice.productName}`);
      //     return navigator.usb.getDevices()
      //     // return usbDevice.open()
      //   })
      //   .then(devices => {
      //     console.log(devices)
      //   })
      //   .catch((e) => {
      //     console.error(`There is no device. ${e}`);
      //   });

      let device;

      let data = new Uint8Array([1]);

      navigator.usb.requestDevice({ filters: [{ vendorId: 7119 }] })
        .then(selectedDevice => {
          console.log(selectedDevice);
          device = selectedDevice;
          console.log(device.name);
          console.log(device.configuration);

          console.log(device.configurations[0]);
          return device.open(); // Begin a session.
        })
        .then(() => device.selectConfiguration(1)) // Select configuration #1 for the device.

        // .then(() => device.transferOut(
        //   7,
        //   data))

        // .then(() => device.transferOut({
        //   requestType: 'class',
        //   recipient: 'interface',
        //   request: 1,
        //   value: 2048,
        //   index: 256
        // }, data)) // Ready to receive data

        // .then(() => device.sendReport(0x01, data)

        // )

        .then(() => device.claimInterface(1)) // Request exclusive control over interface #2.
        .then(() => device.controlTransferOut({
          requestType: 'class',
          recipient: 'interface',
          request: 1,
          value: 2048,
          index: 256
        }, data)) // Ready to receive data
        .then(() => device.transferIn(5, 64)) // Waiting for 64 bytes of data from endpoint #5.
        .then(result => {
          const decoder = new TextDecoder();
          console.log('Received: ' + decoder.decode(result.data));
        })
        .catch(error => { console.error(error); });


    }

    function myFunction(value) {
      // document.getElementById("demo").innerHTML = value; 

      window.open('tel:18728788888', "self");
    }


    var currentCharacteristic
    function connectBluetoothDevice() {


      /* 搜索附近的蓝牙设备 */
      navigator.bluetooth.requestDevice({
        filters: [{
          services: ['0000ffe0-0000-1000-8000-00805f9b34fb']
        }]
      })
        .then(device => {

          console.log(device.name); // 输出设备名称
          device.gatt.connect().then(server => {
            console.log('连接服务器:', server);
            server.getPrimaryServices().then(services => {
              console.log('获取 services' + services);
              let service = services[0];
              service.getCharacteristics().then(characteristics => {
                console.log(characteristics)
                let characteristic = characteristics[0]
                currentCharacteristic = characteristic

                let encoder = new TextEncoder('utf-8');
                let value = encoder.encode("R0458");
                console.log(value);

                characteristic.writeValue(value).then(_ => {
                  console.log('wirte success');
                }).catch(error => {
                  console.log('错误:', error);
                });

              })
            })
          })
        })
        .catch(error => {
          console.log('错误:', error);
        });


    }


    function onDisconnected(event) {
      console.log(currentCharacteristic)
      // const device = event.target;
      // console.log(`设备: ${device.name} 已经断开连接`);
    }

    function turning() {
      console.log(currentCharacteristic)
      let encoder = new TextEncoder('utf-8');
      let value = encoder.encode("L0459");
      console.log(value);

      currentCharacteristic.writeValue(value).then(_ => {
        console.log('wirte success');
      }).catch(error => {
        console.log('错误:', error);
      });
    }


    function getDevicesList(argument) {
      console.log("getDevicesList")

      //   const BlueDeviceType = {
      //     GEMTurntable: 'GEMTurntable',
      //     LabelPrinter: 'LabelPrinter',
      // };
      class Test {

        // constructor(name, year) {
        //   this.name = name;
        //   this.year = year;
        // }
      }

      // let test = new Test(
      //   "xxxx", 123
      // )
      // console.log(test.name)
      // console.log(test.year)

      const WebAppInterfaceErrorCode = {
        Default: 0,
        Camera: {
          authDeny: 1001,
          notFoundGem: 1002,
          notSupportUVC: 1003
        },
        Bluetooth: {
          authDeny: 2001,
          notConnect: 2002
        }
      };

      class CallbackCodeHandle {
        static isSuccess(code) {
          if (code == 1) {
            return true
          }
          return false
        }
        static getCodeType(code) {
          let isSuccess = CallbackCodeHandle.isSuccess(code)
          if (isSuccess) {
            return undefined
          }
          if (code >= 1000 && code < 2000) {
            return WebAppInterfaceErrorCode.Camera
          }
          if (code >= 2000 && code < 3000) {
            return WebAppInterfaceErrorCode.Bluetooth
          }
          return undefined
        }
      }

      var errorCode = 1002;
      errorCode = '1';

      let isSuccess = CallbackCodeHandle.isSuccess(errorCode)
      console.log(isSuccess)

      let type = CallbackCodeHandle.getCodeType(errorCode)
      console.log(type)


      switch (errorCode) {
        case WebAppInterfaceErrorCode.Camera.authDeny:
          console.log("xxx");
          break;
        case WebAppInterfaceErrorCode.Camera.notFoundGem:
          console.log("notFoundGem");
          break;
        default:
          console.log("default")
      }


      navigator.bluetooth.requestDevice({ filters: [{ services: ['0000ffe0-0000-1000-8000-00805f9b34fb'] }] })
        .then(device => {
          console.log(device.name);
        })
        .catch(error => { console.log(error); });

      // console.log(WebAppInterfaceErrorCode.Camera.authDeny)

      // console.log(Color.RED);  // 打印 "red"


      // var param = {functionName : "toggleCameraFocus",
      // deviceName : "xxx",
      // isOpenAutoFocus : true}

      // console.log(param)

      // var jsonText = JSON.stringify(param)
      // console.log(jsonText)

      // var paramArray = {
      //   list : [param, param]
      // }
      // console.log(paramArray)
      // console.log(JSON.stringify(paramArray))


      // var json = '{ "functionName":"Runoob" , "url":"www.runoob.com" }'



      // window.webkit.messageHandlers.AppInterface.postMessage("jsonText");

      // var text = '{ "sites" : [' +
      //     '{ "name":"Runoob" , "url":"www.runoob.com" },' +
      //     '{ "name":"Google" , "url":"www.google.com" },' +
      //     '{ "name":"Taobao" , "url":"www.taobao.com" } ]}';
      // console.log(text)

      // obj = JSON.parse(text);
      // console.log(obj)

      // document.getElementById("demo").innerHTML = obj.sites[1].name + " " + obj.sites[1].url;

    }
  </script>

</body>

</html>